package com.ecnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecnu.common.constant.HttpStatus;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.common.utils.http.UrlUtils;
import com.ecnu.common.utils.uuid.IdUtils;
import com.ecnu.system.domain.ProjectFile;
import com.ecnu.system.domain.dto.FileDTO;
import com.ecnu.system.domain.dto.FileLabelDTO;
import com.ecnu.system.domain.dto.ProjectFileDTO;
import com.ecnu.system.domain.vo.FileLabelVO;
import com.ecnu.system.domain.vo.FileVO;
import com.ecnu.system.mapper.ProjectFileLabelsMapper;
import com.ecnu.system.mapper.ProjectFileMapper;
import com.ecnu.system.service.IProjectFileLabelsService;
import com.ecnu.system.service.IProjectFileService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ecnu.system.domain.menu.OtherMenu.sysUrl;

/**
 * <p>
 * ecnu_活动_资料表 服务实现类
 * </p>
 *
 * @author zdn
 * @since 2025-03-23
 */
@Service
public class ProjectFileServiceImpl extends ServiceImpl<ProjectFileMapper, ProjectFile> implements IProjectFileService {

    @Autowired
    private ProjectFileMapper projectFileMapper;
    @Autowired
    private ProjectFileLabelsMapper fileLabelsMapper;
    @Autowired
    private IProjectFileLabelsService projectFileLabelsService;

    /**
     * 分页查询
     */
    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    protected String getId() {
        return IdUtils.fastSimpleUUID();
    }

    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        rspData.setPageNum(new PageInfo(list).getPageNum());
        rspData.setPageSize(new PageInfo(list).getPageSize());
        return rspData;
    }

    /**
     * 分页查询
     */
    @Override
    public TableDataInfo getList(FileDTO filePram) {
        startPage(filePram.getPageDomain());
//        LambdaQueryWrapper<ProjectFile> wrapper = new LambdaQueryWrapper<>();
//        if (StringUtils.isNotBlank(filePram.getName())) {
//            wrapper.like(ProjectFile::getName, filePram.getName());
//        }
//        wrapper.eq(ProjectFile::getProId, filePram.getProId());
//        wrapper.eq(ProjectFile::getDelFlag, "0");
//        wrapper.orderBy(ProjectFile::getCreateTime, "Desc")
        List<ProjectFile> list = projectFileMapper.selectLists(filePram);
        ArrayList<FileVO> fileVOS = new ArrayList<>();
        if (list.isEmpty()) {// 如果list为空，则返回空列表
            return getDataTable(fileVOS);
        }
        // 遍历list
        for (ProjectFile projectFile : list) {
            FileVO fileVO = new FileVO();
            BeanUtils.copyProperties(projectFile, fileVO); // 单个对象复制
            fileVOS.add(fileVO);
        }

        List<String> fileList = list.stream()
                .map(ProjectFile::getId)
                .collect(Collectors.toList());
        // 查询标签
        List<FileLabelVO> file_id = fileLabelsMapper.labelsList(fileList);

        // 分组
        Map<String, List<FileLabelVO>> fileLabel = file_id.stream()
                .collect(Collectors.groupingBy(FileLabelVO::getFileId));

        fileVOS.forEach(projectListVO -> {
            List<FileLabelVO> teachers = fileLabel.get(projectListVO.getId());
            String userVOs = teachers != null ?
                    teachers.stream()
                            .map(FileLabelVO::getDictValue) // 提取 teachName
                            .collect(Collectors.joining(", ")) : // 用逗号拼接
                    "";
            projectListVO.setLabelsName(userVOs);
            projectListVO.setFullurl(UrlUtils.getUrl()+ projectListVO.getUrl());
        });
        return getDataTable(fileVOS);

    }
//    public String getUrl()
//    {
//        HttpServletRequest request = ServletUtils.getRequest();
//        return getDomain(request);
//    }
//    public static String getDomain(HttpServletRequest request)
//    {
//        StringBuffer url = request.getRequestURL();
//        String contextPath = request.getServletContext().getContextPath();
//        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
//    }

    /**
     * 编辑活动资料
     */
    @Override
    public AjaxResult editFile(ProjectFileDTO projectFile, LoginUser user) {
        try {
            if (StringUtils.isBlank(projectFile.getId())) {
                if (StringUtils.isBlank(projectFile.getName())) {
                    return AjaxResult.error("文件名缺失");
                }
                if (StringUtils.isBlank(projectFile.getUrl())) {
                    return AjaxResult.error("文件路径缺失");
                }
                projectFile.setId(getId());
                projectFile.setCreateUser(user.getUser().getUserId().toString());
                ProjectFile file = new ProjectFile();
                BeanUtils.copyProperties(projectFile, file);

                boolean saved = save(file);
                //标签添加
                if (projectFile.getFileLabels() != null && projectFile.getFileLabels().size() > 0) {
                    //标签添加
                    FileLabelDTO fileLabelDTO = new FileLabelDTO();
                    fileLabelDTO.setFileId(projectFile.getId());
                    fileLabelDTO.setFileLabels(projectFile.getFileLabels());
                    projectFileLabelsService.edit(fileLabelDTO);
                }
                return saved ? AjaxResult.success("保存成功",projectFile.getId()) : AjaxResult.error("保存失败");
            } else {
                ProjectFile file = projectFileMapper.selectOne(
                        new QueryWrapper<ProjectFile>()
                                .eq("id", projectFile.getId())
                                .eq("del_flag", "0"));
                if (file == null) {
                    return AjaxResult.error("文件不存在");
                }
                projectFile.setUpdateUser(user.getUser().getUserId().toString());
                ProjectFile file2 = new ProjectFile();
                BeanUtils.copyProperties(projectFile, file2);
                boolean updated = updateById(file2);
                //标签添加
                if (projectFile.getFileLabels() != null && projectFile.getFileLabels().size() > 0) {
                    //标签添加
                    FileLabelDTO fileLabelDTO = new FileLabelDTO();
                    fileLabelDTO.setFileId(projectFile.getId());
                    fileLabelDTO.setFileLabels(projectFile.getFileLabels());
                    projectFileLabelsService.edit(fileLabelDTO);
                }
                return updated ? AjaxResult.success("保存成功",projectFile.getId()) : AjaxResult.error("保存失败");
            }
        } catch (Exception e) {
            log.error("保存失败,名称:\n" + projectFile.getName() + "错误内容为：\n" + e.getMessage());
            return AjaxResult.error("操作失败");
        }
    }
}
